package com.inspireink.project.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/api/python1")
public class PythonScript1Controller {

    private static final Logger logger = LoggerFactory.getLogger(PythonScript1Controller.class);

    @Value("${python.path}")
    private String pythonPath;

    @Value("${scripts.path}")
    private String scriptsPath;

    @Value("${output.path.api1}")
    private String outputPath;

    private final ResourceLoader resourceLoader;

    public PythonScript1Controller(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostMapping("/executeApi1")
    public ResponseEntity<String> executeApi1(@RequestParam("flowerImage") MultipartFile flowerImage,
                                              @RequestParam("vanpicImage") MultipartFile vanpicImage,
                                              @RequestParam("subjectpos") String subjectpos,
                                              @RequestParam("subjectneg") String subjectneg,
                                              @RequestParam("backgroundpos") String backgroundpos,
                                              @RequestParam("backgroundneg") String backgroundneg) {
        try {
            // 保存上传的图片到临时目录
            Path flowerImagePath = saveFile(flowerImage, "flower.png");
            Path vanpicImagePath = saveFile(vanpicImage, "Vanpic.jpg");

            // 加载脚本文件和 JSON 文件
            Resource scriptResource = resourceLoader.getResource(scriptsPath + "/api1.py");
            File scriptFile = scriptResource.getFile();
            Resource jsonResource = resourceLoader.getResource(scriptsPath + "/Inspire_Ink_1_API.json");
            File jsonFile = jsonResource.getFile();

            // 生成随机种子
            Random random = new Random();
            Map<String, Long> seeds = new HashMap<>();
            seeds.put("subjectseed_1", random.nextLong(999999999999999L) + 1);
            seeds.put("subjectseed_2", random.nextLong(999999999999999L) + 1);
            seeds.put("subjectseed_3", random.nextLong(999999999999999L) + 1);
            seeds.put("subjectseed_4", random.nextLong(999999999999999L) + 1);
            seeds.put("backgroundseed_1", random.nextLong(999999999999999L) + 1);
            seeds.put("backgroundseed_2", random.nextLong(999999999999999L) + 1);
            seeds.put("backgroundseed_3", random.nextLong(999999999999999L) + 1);
            seeds.put("backgroundseed_4", random.nextLong(999999999999999L) + 1);

            // 日志记录
            logger.info("Python Path: " + pythonPath);
            logger.info("Script File: " + scriptFile.getAbsolutePath());
            logger.info("Flower Image Path: " + flowerImagePath.toString());
            logger.info("Vanpic Image Path: " + vanpicImagePath.toString());
            logger.info("Output Path: " + outputPath);
            logger.info("JSON File: " + jsonFile.getAbsolutePath());
            seeds.forEach((key, value) -> logger.info(key + ": " + value));

            // 确保输出目录存在
            File outputDir = new File(outputPath);
            if (!outputDir.exists()) {
                Files.createDirectories(outputDir.toPath());
            }

            // 执行 Python 脚本
            ProcessBuilder processBuilder = new ProcessBuilder(
                    pythonPath,
                    scriptFile.getAbsolutePath(),
                    flowerImagePath.toString(),
                    vanpicImagePath.toString(),
                    subjectpos,
                    subjectneg,
                    backgroundpos,
                    backgroundneg,
                    seeds.get("subjectseed_1").toString(),
                    seeds.get("subjectseed_2").toString(),
                    seeds.get("subjectseed_3").toString(),
                    seeds.get("subjectseed_4").toString(),
                    seeds.get("backgroundseed_1").toString(),
                    seeds.get("backgroundseed_2").toString(),
                    seeds.get("backgroundseed_3").toString(),
                    seeds.get("backgroundseed_4").toString(),
                    outputDir.getAbsolutePath(),
                    jsonFile.getAbsolutePath()
            );
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            // 读取进程输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            process.waitFor();

            // 日志记录输出
            logger.info("Python script output: " + output.toString());

            // 检查输出文件夹中的生成图像
            if (outputDir.exists() && outputDir.isDirectory()) {
                File[] outputFiles = outputDir.listFiles();
                if (outputFiles != null && outputFiles.length > 0) {
                    // 返回生成的图像文件名列表
                    StringBuilder result = new StringBuilder("Generated images: ");
                    for (File file : outputFiles) {
                        result.append(file.getName()).append(" ");
                    }
                    return ResponseEntity.ok(result.toString());
                }
            }

            return ResponseEntity.status(500).body("Failed to generate images");
        } catch (IOException | InterruptedException e) {
            logger.error("Error executing Python script", e);
            return ResponseEntity.status(500).body("Error executing Python script: " + e.getMessage());
        }
    }

    private Path saveFile(MultipartFile file, String filename) throws IOException {
        Path filePath = Paths.get(System.getProperty("java.io.tmpdir"), filename);
        file.transferTo(filePath);
        return filePath;
    }
}